package com.itheima.d6_tcp3;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;


public class MyThread extends Thread {
    private Socket socket;

    public MyThread(Socket socket) {
        this.socket = socket;
    }



    @Override
    public void run() {

        try {
            //5.读取数据
            while (true) {
                DataInputStream dis = null;
                try {
                    //3.获取输入流，接收数据
                    InputStream is = socket.getInputStream();
                    //4.特殊数据流包装
                    dis = new DataInputStream(is);
                    String msg = dis.readUTF();
                    System.out.println("服务器收到的信息:" + msg);
                    System.out.println("对方IP地址:" + socket.getInetAddress().getHostAddress());
                    System.out.println("对方端口:" + socket.getPort());
                    System.out.println("===========================");
                    //TODO: 群聊
                    //拓展：群聊 所以要把信息发给客户端
                    sendMsgToAll(msg);
                } catch (Exception e) {
                    System.out.println("客户端已下线...IP是:" + socket.getInetAddress().getHostAddress());
                    if (dis != null) {
                        break;
                    } else {
                        dis.close();
                        //TODO
                        // 把下线的socket从集合中删除
                        Server.onlineSocket.remove(socket);
                        socket.close();
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private void sendMsgToAll(String msg) throws IOException {
        for (Socket socket1 : Server.onlineSocket) {
            //创建输出流
            OutputStream os = socket1.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(msg);
            dos.flush();
        }


    }
}
